package com.ewili.x.special.task.thread.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ewili.framework.utils.MathUtils;
import com.ewili.framework.utils.ObjectHttpClientUtils;
import com.ewili.x.special.dao.inter.BlockTradingMarketDao;
import com.ewili.x.special.entity.BlockTradingMarket;
import com.ewili.x.special.task.thread.inter.BlockTradingMarketThreadTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class BlockTradingMarketThreadTaskImpl implements BlockTradingMarketThreadTask {

    @Autowired
    private BlockTradingMarketDao blockTradingMarketDao;

    //@Async("myTaskAsyncPool")
    @Override
    public void blockTradingMarket(String doUrl) {
        JSONArray objs = ObjectHttpClientUtils.formatEastMoneyFormatData(doUrl, "data:", "]}");
        for (int i = 0; i < objs.size(); i++) {
            JSONObject jsonObject = objs.getJSONObject(i);
            Date date = jsonObject.getDate("TDATE");
            Double ssei = jsonObject.getDouble("SZZS");
            Double changeRate = jsonObject.getDouble("SZZDF");
            Double blockTradingMarketAmount = jsonObject.getDouble("CJZE");
            Double premiumTransactionAmount = jsonObject.getDouble("YJCJZE");
            Double premiumTransactionRate = jsonObject.getDouble("YJCJZERate");
            Double discountTransactionAmount = jsonObject.getDouble("ZJCJZE");
            Double discountTransactionRate = jsonObject.getDouble("ZJCJZERate");
            Double preSubDis = MathUtils.subtract(premiumTransactionRate, discountTransactionRate);

            boolean isDateExists = blockTradingMarketDao.existsByDate(date);
            if (isDateExists) {
                continue;
            }

            BlockTradingMarket blockTradingMarket = new BlockTradingMarket();
            blockTradingMarket.setDate(date);
            blockTradingMarket.setSsei(ssei);
            blockTradingMarket.setChangeRate(changeRate);
            blockTradingMarket.setBlockTradingMarketAmount(blockTradingMarketAmount);
            blockTradingMarket.setPremiumTransactionAmount(premiumTransactionAmount);
            blockTradingMarket.setPremiumTransactionRate(premiumTransactionRate);
            blockTradingMarket.setDiscountTransactionAmount(discountTransactionAmount);
            blockTradingMarket.setDiscountTransactionRate(discountTransactionRate);
            blockTradingMarket.setPreSubDis(preSubDis);

            blockTradingMarketDao.save(blockTradingMarket);
        }
    }
}
